<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>2018A14133黄仙龙</title>
    <script src="js/mqtt.min.js"></script> <!-- 引处MQTT.MINI.JS库文件 -->
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="js/bootstrap/css/bootstrap.min.css">
    <script src="js/jquery-2.1.4.min.js"></script>
    <script src="js/jquery.cookie.min.js"></script>
    <link rel="stylesheet" href="css/style.css" crossorigin="anonymous">
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="js/bootstrap/js/bootstrap.min.js"></script>
    <script src="js/vue.js"></script>
    <!-- <script src="js/app.js"></script> -->
</head>
<body>
    <div class="container text-center">
        <h1>开关控制</h1>
    </div>
    <br>
    <div class="container text-center">
        <button type="button" id="ledRedOn" class="btn btn-success btn-lg" onclick="open_greenswitch()">绿灯开</button>
        <button type="button" id="ledRedOff" class="btn btn-info btn-lg" onclick="close_greenswitch()">绿灯关</button>
    </div>
    <br>
    <div class="container text-center">
        <button type="button" id="ledGreenOn" class="btn btn-success btn-lg" onclick="open_redswitch()">红灯开</button>
        <button type="button" id="ledGreenOff" class="btn btn-info btn-lg" onclick="close_redswitch()">红灯关</button>
    </div>
    <br>
    <div class="container text-center">
        <button type="button" id="ledBlueOn" class="btn btn-success btn-lg" onclick="open_blueswitch()">蓝灯开</button>
        <button type="button" id="ledBlueOff" class="btn btn-info btn-lg" onclick="close_blueswitch()">蓝灯关</button>
    </div>
    <br>
    <div class="container text-center">
        <button type="button" id="ledBlueOn" class="btn btn-success btn-lg" onclick="open_allswitch()">全开</button>
        <button type="button" id="ledBlueOff" class="btn btn-info btn-lg" onclick="close_allswitch()">全关</button>
    </div> 
    <!-- 数据接收开始 -->
    <div class="receiveData left text-center">
        <h3>消息接收&nbsp;&nbsp;&nbsp;<button class="receiveClear">清除</button></h3>
        <textarea class="receiveArea" name="" id="" cols="85" rows="30"></textarea>
    </div>
    <!-- 数据接收结束 -->
</body>
<script>
    let receiveClear = document.getElementsByClassName('receiveClear')[0];
    let receiveArea = document.getElementsByClassName('receiveArea')[0];

    var topic_chat = '2018A14133/chat';
    var topic_switch = '2018A14133/switch';  //定义两个topic（聊天topict和开关topic）

    //连接选项，mqtt用户名和密码，这里面应该还可以加上其他参数，具体看官方文档: https://www.npmjs.com/package/mqtt#connect 和https://github.com/mqttjs/mqtt-packet#connect
    const options = {
        connectTimeout: 4000, // 超时时间
        username: '602iot',
        password: '602iot',
        clientId: 'mqttjs_' + (Math.random() * 1000000).toString()
    }

    //浏览器采用websocket协议，路径固定为/mqtt 【此处请定义mqtt客户端client、声明重连和连接失败报错】
    const client = mqtt.connect('ws://red263b0.cn.emqx.cloud:8083/mqtt', options)//EMQ X Cloud平台的连接地址
    client.on('reconnect', (error) => {
        console.log('正在重连:', error)
    })

    client.on('error', (error) => {
        console.log('连接失败:', error)
    })

    //建立连接 【此处请建立mqtt连接，并订阅上方定义的两个topic，友情提示：帖子示例中onSubscribeSuccess要加上引号】
    client.on('connect', (e) => {
        console.log('成功连接服务器！')
        client.publish(topic_chat, '成功连接服务器！');
    })

    // 订阅多个主题			
    client.subscribe([topic_chat, topic_switch], { qos: 0 }, 'onSubscribeSuccess', (error) => {
        if (!error) {
            console.log('订阅成功！')
            client.publish(topic_chat, '主题订阅成功！', { qos: 0, rein: false }, (error) => {
                console.log(error || '发布成功！')
            })
        }
    })

    // 定义开启绿灯函数  function open_greenswitch()
    function open_greenswitch() {
        client.publish(topic_switch, 'Green led on');
    }

    // 定义关闭绿灯函数  function close_greenswitch()
    function close_greenswitch() {
        client.publish(topic_switch, 'Green led off');
    }

    //定义开启红灯函数  function open_redswitch()
    function open_redswitch() {
        client.publish(topic_switch, 'Red led on');
    }

    // 定义关闭红灯函数  function close_redswitch()
    function close_redswitch() {
        client.publish(topic_switch, 'Red led off');
    }

    //定义开启蓝灯函数  function open_blueswitch()
    function open_blueswitch() {
        client.publish(topic_switch, 'Blue led on');
    }

    //定义关闭蓝灯函数  function close_blueswitch()
    function close_blueswitch() {
        client.publish(topic_switch, 'Blue led off');
    }

    //定义开启蓝灯函数  function open_allswitch()
    function open_allswitch() {
        client.publish(topic_switch, 'All on');
    }

    //定义关闭蓝灯函数  function close_allswitch()
    function close_allswitch() {
        client.publish(topic_switch, 'All off');
    }

    //定义一个时间格式化的方法
    function formartDate(date) {
        return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
    }

    // 16进制数,转为字符串显示
    function hex2str(hex) {
        let str = '';
        let i;
        for (i = 0; i < hex.length; i++) {
            if (hex[i] <= 15) {
                str = str + "0" + (hex[i].toString(16) + " ")
            } else {
                str = str + (hex[i].toString(16) + " ")
            }
        }
        return str;
    }

    //实现textarea多行文本框中接收和显示消息 //1.同时监听显示两个topic的内容 2.文本框多行自动滚动功能
    client.on('message', (topic, message) => {
        console.log('收到来自', topic, '的消息', message.toString())
    })
    client.on('message', (topic, message) => {//接收到消息
        //console.log("onMessageArrived:"+message.payloadString);
        receiveArea.append("\r\n" + formartDate(new Date()));
        receiveArea.append("\r\n" + '主题:' + topic);
        try {//字符串显示
            receiveArea.append("\r\n" + '字符串消息:');
            receiveArea.append(message);
            receiveArea.append("\r\n");
        } catch (e) {
            receiveArea.append("\r\n");
        }

        try {//16进制显示
            receiveArea.append('16进制消息:');
            receiveArea.append(hex2str(message) + "\r\n");
            receiveArea.append("\r\n");
            //console.log(message.payloadBytes);
        } catch (e) {
            receiveArea.append("\r\n");
        }
        receiveArea.scrollTop = receiveArea.scrollHeight;
    })

    //监听数据接收清除按钮的点击 实现多行文本框内容清空
    receiveClear.onclick = function () {
        receiveArea.innerHTML = '';
    }

</script>
</html>